<template>
  <div style="margin-top: 20px;height:calc(100vh - 86px);overflow-y:auto;">
    <el-form ref="elForm" :model="formData" size="medium" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" placeholder="标题" maxlength="30" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="描述">
            <el-input v-model="formData.intro" type="textarea" placeholder="请输入网站描述"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="视频上传">
            <el-upload
              multiple
              :action="uploadImgUrl"
              :before-upload="handleAttachmentBeforeUpload"
              :file-list="attachmentList"
              :limit="limit"
              :on-error="handleAttachmentUploadError"
              :on-exceed="handleAttachmentExceed"
              :on-success="handleAttachmentUploadSuccess"
              :show-file-list="false"
              :headers="headers"
              class="upload-file-uploader"
              ref="fileUpload"
            >
              <!-- 上传按钮 -->
              <el-button size="mini" type="primary">选取文件</el-button>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="attachmentfileType"> 格式为 <b style="color: #f56c6c">{{ attachmentfileType.join("/") }}</b> </template>
                的文件
              </div>
            </el-upload>

            <!-- 文件列表 -->
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
              <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in attachmentList">
                <el-link :underline="false" :href="`${file.url}`" target="_blank">
                  <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
                </el-link>
                <div class="ele-upload-list__item-content-action">
                  <el-link :underline="false" @click="handleAttachmentDeleteFile(index)" type="danger">删除</el-link>
                </div>
              </li>
            </transition-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {getInfoByType, editArticle} from "@/api/system/article";
import {getSite, getToken} from "@/utils/auth"
import {listToString, splitImages} from "@/api/tool/upload";

export default {
  name: "Home",
  components: {},
  props: {
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    attachmentfileType: {
      type: Array,
      default: () => ["mp4"],
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
  },
  data() {
    return {
      formData: {
        title: '',
        content: undefined,
        articleType: 8,
        cateId: 2,
      },
      // 查询参数
      queryParams: {
        tenantId: getSite(),
        articleType: 8,
        typeId: 2,
        cateId: 2

      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 上传的图片服务器地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传图片个数
      number: 0,
      attachmentList: [], //附件上传
      contentIconList: [], //介绍icon
      imageList: [],  //列表缩略图
      uploadList: [], //临时上传列表
      dialogVisible: false,
      dialogImageUrl: "",
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  watch: {},
  created() {
    this.getDetail();
  },
  mounted() {},
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.formData.tenantId = this.queryParams.tenantId;
        this.formData.articleType = this.queryParams.articleType;
        this.formData.cateId = this.queryParams.cateId;
        this.formData.typeId = this.queryParams.typeId;
        // logo
        this.formData.images = splitImages(this.imageList);
        //logo背景图
        this.formData.linkUrl = splitImages(this.contentIconList);
        //附件
        this.formData.attachment = splitImages(this.attachmentList);


        editArticle(this.formData).then(response => {
          this.$modal.msgSuccess("更新成功");
          this.open = false;
          this.getDetail();
        });
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields();
      this.formData.content = undefined;
    },
    getDetail(){
      getInfoByType(this.queryParams).then(response => {
        this.formData = response.data;
        //荣誉icon
        this.imageList = [];
        if(this.formData.images){
          const imageArr = this.formData.images.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.imageList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //体系icon
        this.contentIconList = [];
        if(this.formData.linkUrl){
          const imageArr = this.formData.linkUrl.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.contentIconList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //附件
        this.attachmentList = [];
        if(this.formData.attachment){
          const imageArr = this.formData.attachment.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.attachmentList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
      });
    },
    //附件上传
    // 上传前loading加载
    handleAttachmentBeforeUpload(file) {
      let isImg = false;
      if (this.attachmentfileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.attachmentfileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.attachmentfileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleAttachmentUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedAttachmentSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedAttachmentSuccessfully();
      }
    },
    // 上传结束处理
    uploadedAttachmentSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.attachmentList = this.attachmentList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.attachmentList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleAttachmentExceed() {
      this.$modal.msgError(`附件上传数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleAttachmentUploadError() {
      this.$modal.msgError("上传附件失败，请重试");
      this.$modal.closeLoading();
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 删除文件
    handleAttachmentDeleteFile(index) {
      this.attachmentList.splice(index, 1);
      this.$emit("input", listToString(this.attachmentList));
    },

    //分类图片方法
    // 上传前loading加载
    handleCateImageBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadCateImageSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedCateImageSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedCateImageSuccessfully();
      }
    },
    // 上传结束处理
    uploadedCateImageSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.imageList = this.imageList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.imageList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleCateImageExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleCateImageUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleCateImageUploadDelete(file) {
      const findex = this.imageList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.imageList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.imageList));
      }
    },
    // 预览
    handleCateImagePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //介绍ICON图片上传
    // 上传前loading加载
    handleContentIconBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadContentIconSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedContentIconSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedContentIconSuccessfully();
      }
    },
    // 上传结束处理
    uploadedContentIconSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.contentIconList = this.contentIconList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.contentIconList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleContentIconExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleContentIconUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleContentIconUploadDelete(file) {
      const findex = this.contentIconList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.contentIconList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.contentIconList));
      }
    },
  }
}

</script>
<style>
</style>
